package config.spring.boot.starter;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * StarterAutoConfigure
 *
 * @author ybtccc
 * @date 2019/2/20
 */
@Configuration
@ConditionalOnClass(ConfigListener.class)
public class StarterAutoConfigure {
    private static Logger logger = LoggerFactory.getLogger(StarterAutoConfigure.class);

    @Bean(initMethod = "start")
    public CuratorFramework zkClient(@Value("${my-config.zk.url}") String url, @Value("${spring.application.name}") String namespace) {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder().namespace("myConfig/" + namespace)
                .connectString(url)
                .retryPolicy(retryPolicy)
                .build();
        return client;
    }

    @Bean(initMethod = "start", destroyMethod = "stop")
    public ConfigListener configListener(@Autowired CuratorFramework zkClient) {
        return new ConfigListener(zkClient);
    }
}
